package com.dfbz.demo02_图片上传案例;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.UUID;

/**
 * @author lscl
 * @version 1.0
 * @intro:
 */
public class Demo03_Server_多线程 {
    public static void main(String[] args) throws Exception {

        // 创建一个服务器
        ServerSocket serverSocket = new ServerSocket(8888);

        while (true) {
            // 接收到一个客户端
            Socket client = serverSocket.accept();

            System.out.println("客户端【" + client.getInetAddress().getHostAddress() + "】连接成功啦！");
            new Thread() {
                @Override
                public void run() {

                    try {
                        // 获取与客户端的输入流(用于读取客户端发送过来的字节)
                        InputStream is = client.getInputStream();

                        // 关联本地的一个文件
                        FileOutputStream fos = new FileOutputStream(UUID.randomUUID() + ".png");

                        byte[] data = new byte[8192];
                        int len;
                        while ((len = is.read(data)) != -1) {
                            fos.write(data, 0, len);
                        }

                        fos.close();
                        client.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }.start();
        }
    }
}
